package org.dealpdf.utils;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.dealpdf.model.OutboundDetail;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

// PDF 文档操作工具类
public class PdfUtil {
    /**
     * 在 PDF 中添加二维码
     * @param canvas PDF 内容层
     * @param qrContent 二维码内容
     * @throws IOException 输入输出异常
     * @throws DocumentException 文档异常
     */
    public static void addQRCode(PdfContentByte canvas, String qrContent) throws IOException, com.google.zxing.WriterException, DocumentException {
        int size = 100;
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, size, size);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", baos);
        Image qrImage = Image.getInstance(baos.toByteArray());
        qrImage.scaleToFit(size, size);
        float x = canvas.getPdfDocument().getPageSize().getWidth() - size - 10f;
        float y = canvas.getPdfDocument().getPageSize().getHeight() - qrImage.getScaledHeight() - 10f;
        qrImage.setAbsolutePosition(x, y);
        canvas.addImage(qrImage);
    }

    /**
     * 在 PDF 中添加水印
     * @param stamper PDF 模板对象
     * @param watermarkText 水印文本
     * @throws IOException 输入输出异常
     * @throws DocumentException 文档异常
     */
    public static void addWatermark(PdfStamper stamper, String watermarkText) throws IOException, DocumentException {
        PdfContentByte under = stamper.getUnderContent(1);
        com.itextpdf.text.pdf.BaseFont baseFont = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
        under.saveState();
        com.itextpdf.text.pdf.PdfGState gs1 = new com.itextpdf.text.pdf.PdfGState();
        gs1.setFillOpacity(0.1f);
        under.setGState(gs1);
        under.beginText();
        under.setFontAndSize(baseFont, 60);
        under.setColorFill(com.itextpdf.text.BaseColor.LIGHT_GRAY);
        float pageWidth = stamper.getReader().getPageSize(1).getWidth();
        float pageHeight = stamper.getReader().getPageSize(1).getHeight();
        for (float x = -100; x < pageWidth + 100; x += 200) {
            for (float y = -100; y < pageHeight + 100; y += 150) {
                under.showTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45);
            }
        }
        under.endText();
        under.restoreState();
    }

    /**
     * 替换 PDF 中的表单字段
     * @param stamper PDF 模板对象
     * @param data 包含键值对的 Map，键为字段名，值为替换内容
     * @throws IOException 输入输出异常
     * @throws DocumentException 文档异常
     */
    public static void replacePlaceholders(PdfStamper stamper, Map<String, String> data) throws IOException, DocumentException {
        com.itextpdf.text.pdf.AcroFields form = stamper.getAcroFields();
        System.out.println("Available fields: " + form.getFields().keySet()); // 调试输出
        for (Map.Entry<String, String> entry : data.entrySet()) {
            if (form.getField(entry.getKey()) != null) {
                form.setField(entry.getKey(), entry.getValue());
            } else {
                System.out.println("Field not found: " + entry.getKey()); // 调试未找到字段
            }
        }
    }

    /**
     * 动态生成出库明细表格
     * @param canvas PDF 内容层
     * @param details 出库明细数据列表
     * @throws DocumentException 文档异常
     */
    public static void addTable(PdfContentByte canvas, List<OutboundDetail> details) throws DocumentException, IOException {
        float margin = 50;
        float baseInfoHeight = 150; // 基础信息高度
        float tableOffset = 250; // 向下移动 250 像素
        float tableTop = canvas.getPdfDocument().getPageSize().getHeight() - margin - baseInfoHeight - tableOffset;
        float tableLeft = margin;
        float cellHeight = 20;
        float cellWidth = (canvas.getPdfDocument().getPageSize().getWidth() - 2 * margin) / 7;

        // 设置字体和颜色
        com.itextpdf.text.pdf.BaseFont baseFont = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
        canvas.setColorFill(com.itextpdf.text.BaseColor.WHITE); // 背景设为白色

        // 填充表格背景
        canvas.rectangle(tableLeft, tableTop - (details.size() + 1) * cellHeight, cellWidth * 7, (details.size() + 1) * cellHeight);
        canvas.fill();

        // 绘制表头
        String[] headers = {"序号", "订单号", "订单明细号", "产品名称", "单位", "数量", "单价"};
        float y = tableTop;
        canvas.setColorStroke(com.itextpdf.text.BaseColor.BLACK); // 边框颜色
        for (int i = 0; i < headers.length; i++) {
            canvas.rectangle(tableLeft + i * cellWidth, y - cellHeight, cellWidth, cellHeight);
        }
        canvas.stroke(); // 仅绘制边框
        canvas.beginText();
        canvas.setFontAndSize(baseFont, 12);
        canvas.setColorFill(com.itextpdf.text.BaseColor.BLACK); // 文本颜色
        for (int i = 0; i < headers.length; i++) {
            canvas.showTextAligned(Element.ALIGN_CENTER, headers[i], tableLeft + i * cellWidth + cellWidth / 2, y - cellHeight / 2, 0);
        }
        canvas.endText();

        // 绘制数据行
        y -= cellHeight;
        for (int i = 0; i < details.size(); i++) {
            OutboundDetail detail = details.get(i);
            String[] values = {
                    String.valueOf(i + 1),
                    detail.getOrderId(),
                    detail.getDetailId(),
                    detail.getProductName(),
                    detail.getUnit(),
                    String.valueOf(detail.getQuantity()),
                    String.format("%.2f", detail.getUnitPrice())
            };
            for (int j = 0; j < values.length; j++) {
                canvas.rectangle(tableLeft + j * cellWidth, y - cellHeight, cellWidth, cellHeight);
            }
            canvas.stroke();
            canvas.beginText();
            for (int j = 0; j < values.length; j++) {
                canvas.showTextAligned(Element.ALIGN_CENTER, values[j], tableLeft + j * cellWidth + cellWidth / 2, y - cellHeight / 2, 0);
                System.out.println("Table cell [" + i + "," + j + "]: " + values[j]); // 调试输出
            }
            canvas.endText();
            y -= cellHeight;
        }
    }
}